﻿using Microsoft.AspNetCore.SignalR;

namespace Demo.SignalRClient.Razor.SignalRHubs
{
    public class ChatHub:Hub
    {

        /// <summary>
        /// 广播发送
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }

        /// <summary>
        /// 指定群组发送
        /// </summary>
        /// <param name="user"></param>
        /// <param name="message"></param>
        /// <returns></returns> 
        public async Task SendMessageToGroup(string groupName, string message)
        {
            await Clients.Group(groupName).SendAsync("ReceiveMessage", message);
        }

        /// <summary>
        /// 指定用户发送
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToUser(string userId, string message)
        {
            await Clients.User(userId).SendAsync("ReceiveMessage", message);
        }

        /// <summary>
        /// 用户连接
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            // 可以在这里将用户加入某个组
            await base.OnConnectedAsync();
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            // 可以在这里处理用户断开连接的逻辑
            await base.OnDisconnectedAsync(exception);
        }


    }
}
